<template>
  <div class="app-container">
    <el-form ref="majorFrom" :model="majorFrom" :rules="rules" label-width="120px">
      <el-form-item label="所属学院" prop="collegeId">
        <CollegeSelect v-model="majorFrom.collegeId" />
      </el-form-item>
      <el-form-item label="专业号" prop="id">
        <el-input
          ref="id"
          v-model="majorFrom.id"
          placeholder="请输入专业号"
          type="text"
        />
      </el-form-item>
      <el-form-item label="专业名" prop="majorName">
        <el-input
          ref="majorName"
          v-model="majorFrom.majorName"
          placeholder="请输入专业名"
          type="text"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAddMajor">新增</el-button>
        <el-button @click="handleResetFrom">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { CollegeSelect } from '@/views/admin/import'
import { majorIdPattern, majorNamePattern } from '@/utils/validate'
import { addMajor } from '@/api/admin/major'

export default {
  name: 'AddMajor',
  components: { CollegeSelect },
  data() {
    return {
      majorFrom: {
        id: '',
        collegeId: undefined,
        majorName: ''
      },
      rules: {
        id: [
          { required: true, message: '请输入专业号', trigger: 'blur' },
          { pattern: majorIdPattern, message: '专业号必须为5位数字', trigger: 'blur' }
        ],
        collegeId: [{ required: true, message: '请选择所属学院', trigger: 'blur' }],
        majorName: [
          { required: true, message: '请输入专业名', trigger: 'blur' },
          { pattern: majorNamePattern, message: '专业名必须为中文不超过30个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /**
     * 新增班级信息
     */
    handleAddMajor() {
      this.$refs.majorFrom.validate(async valid => {
        if (valid) {
          await addMajor(this.majorFrom)
          this.$message.success('新增成功')
          this.handleResetFrom()
        }
      })
    },
    /**
     * 重置表单
     */
    handleResetFrom() {
      this.$refs.majorFrom.resetFields()
    }
  }
}
</script>
